package game;

import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

public class GamePanel extends JPanel implements KeyListener {
    private BufferedImage background;
    private boolean gameRunning = true;

    public GamePanel() {
        setFocusable(true);
        addKeyListener(this);

        // 加载背景图片
        try {
            background = ImageIO.read(new File("resources/background.png"));
        } catch (IOException e) {
            System.out.println("无法加载背景图片，使用纯色背景");
            background = null;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // 绘制背景
        if (background != null) {
            g2d.drawImage(background, 0, 0, getWidth(), getHeight(), null);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }

        // 绘制游戏元素
        drawGameElements(g2d);

        // 绘制UI
        drawUI(g2d);
    }

    private void drawGameElements(Graphics2D g2d) {
        // 在这里绘制角色、特效等游戏元素
        // 例如：
        g2d.setColor(Color.RED);
        g2d.fillRect(100, 400, 50, 100); // 玩家角色
        g2d.setColor(Color.BLUE);
        g2d.fillRect(650, 400, 50, 100); // 敌人角色
    }

    private void drawUI(Graphics2D g2d) {
        // 绘制血条
        g2d.setColor(Color.RED);
        g2d.fillRect(50, 30, 200, 20); // 敌人血条背景
        g2d.setColor(Color.GREEN);
        g2d.fillRect(50, 30, 150, 20); // 敌人当前血量

        g2d.setColor(Color.RED);
        g2d.fillRect(550, 30, 200, 20); // 玩家血条背景
        g2d.setColor(Color.GREEN);
        g2d.fillRect(550, 30, 180, 20); // 玩家当前血量

        // 绘制分数或其他UI元素
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 20));
        g2d.drawString("TIME: 99", 350, 30);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // 处理按键按下事件
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // 处理按键释放事件
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    public void update() {
        // 更新游戏状态
        repaint();
    }
}
